import React from 'react';
import {Button, Dialog, Radio, Form, Checkbox, Select, Input, MessageBox} from 'element-react'

import Top from './../top/index';
import Nav from './../nav/index';
import DateSelect from './../common/date/index';
import SelectAddress from './../common/select_address/index';
import TableShow from './../common/table_show/index';

import axios from 'axios';

import './../../assets/css/substationForm.css'
import './../../assets/css/dialog.css'

class SubstationForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            //选择框
            substation: [{value: 0, label: '请选择'}],
            classic: [{value: 0, label: '请选择'}],
            datevalue1: null,
            datevalue2: null,
            //搜索条件
            recycleTypeId: "",
            beginTime: 0,
            endTime: 0,
            dialogVisible3: false,
            dialogVisible: false,
            disabled: false,
            daochu: [{value: 'Excel'}],
            value: 0,
            columns: [
                {
                    type: 'index',
                    label: '序号',
                },
                {
                    label: "分站",
                    prop: "subName"
                },
                {
                    label: '再回收资源品类',
                    prop: 'recycleTypeName'
                },
                {
                    label: "回收重量(kg)",
                    prop: "recycleWeight",
                    render(data) {
                        return (<span>{(data.recycleWeight / 1000).toFixed(2)}</span>)
                    }
                },
                {
                    label: "回收支出(元)",
                    prop: "recycleExpend",
                    render(data) {
                        return (<span>{(data.recycleExpend / 100).toFixed(2)}</span>)
                    }

                },
                {
                    label: "销售重量(kg)",
                    prop: "salesWeight",
                    render(data) {
                        return (<span>{(data.salesWeight / 1000).toFixed(2)}</span>)
                    }
                }
            ],
            data: [],
            total: 0,
            pageNum: 1,
            pageSize: 20,

            //导出
            exportValue: "3",
            exportFields: ["分站",'再回收资源品类','回收重量(kg)','回收支出(元)','销售重量(kg)'],
            curPage: 1, //当前页
            checkboxData: [ //导出字段数据
                {
                    name: '分站',
                    type: 'subName',
                }, {
                    name: '再回收资源品类',
                    type: 'recycleTypeName',
                }, {
                    name: '回收重量(kg)',
                    type: 'recycleWeight',
                }, {
                    name: '回收支出(元)',
                    type: 'recycleExpend',
                }, {
                    name: '销售重量(kg)',
                    type: 'salesWeight',
                }
            ],
            subIdArr: [],
            isTypeNull: 0,
            isSubShow: 1,
            isSalesWeightShow: 0,
            isRecycleExpendShow: 0,
            isRecycleWeightShow: 0,
            isTypeShow: 0,
            //导出分页
            beginPage: 1,
            endPage: 1,
            beginValue:1,
            endValue:1,
            totalPage:1,
            dialogInfo: ''
        };
        this.dateChange1 = this.dateChange1.bind(this);
        this.dateChange2 = this.dateChange2.bind(this);
        this.searching = this.searching.bind(this);
        this.substationChange = this.substationChange.bind(this);
        this.classicChange = this.classicChange.bind(this);
        this.setPageSize = this.setPageSize.bind(this);
        this.setPageNum = this.setPageNum.bind(this);
        this.selectCheckbox = this.selectCheckbox.bind(this);
        this.getSubStation = this.getSubStation.bind(this);
    }

    componentDidMount() {
        this.getAllId();
        this.getRecycleInfo();

        //时间格式转化
        Date.prototype.toLocaleString = function () {
            return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate();
        };
    }

    getAllId() {
        //数据获取
        axios.post('count/count/subsandpkgs').then((res) => {
            console.log(res);
            //分站列表
            if(res.data.code == 0){
                const substation = new Array(res.data.data.length);
                const subIdArr = [];
                res.data.data.forEach((item, index) => {
                    subIdArr.push(item.id)
                });
                res.data.data.forEach((item, index) => {
                    substation[index] = {
                        value: item.id,
                        label: item.name
                    }
                });
                substation.unshift({
                    value: subIdArr,
                    label: '选择全部'
                });
                this.setState({
                    substation: substation,
                    subIdArr: subIdArr
                });

                this.getSubStation(this.state.pageSize, this.state.pageNum, this.state.subIdArr);
            }else if(res.data.code == -111){
                MessageBox.alert(res.msg);
            } else {
                this.props.history.push('/login')
            }
        }).catch((err) => {
            console.log(err);
        });

    }

    //设置pagesize，pagenum
    setPageNum(size = this.state.pageSize, num = this.state.pageNum) {
        this.setState({pageNum: num, curPage: num});
        this.getSubStation(this.state.pageSize, num, this.state.subIdArr)
    }

    setPageSize(size = 10, num = 1) {
        this.setState({pageSize: size});
        this.getSubStation(size, this.state.pageNum, this.state.subIdArr);
    }

    //数据列表
    getSubStation(size, num, arr = []) {
        axios.post('/count/count/substatistics', {
            'pageSize': size,
            'pageNum': num,
            'subList': arr,
            'isTypeNull': this.state.isTypeNull
        }).then((res) => {
            console.log(res);
            if (res.status === 200 && res.data.code === 0) {
                const countList = res.data.data.pageInfo.list;
                this.setState({
                    total: res.data.data.pageInfo.total,
                    data: countList,
                    endPage: Math.ceil(res.data.data.pageInfo.total / size)
                });
            }else if(res.data.code == -111){
                MessageBox.alert(res.msg);
            } else {
                this.props.history.push('/login')
            }

        }).catch((e) => {
            console.log(e)
        })
    }

    //dataChange  日期插件
    dateChange1 = (date => {
        let beginTime = new Date(date).toLocaleString();
        if (beginTime === '1970-1-1') {
            beginTime = ''
        }
        this.setState({beginTime: beginTime, datevalue1: date})
    });
    dateChange2 = (date => {
        let endTime = new Date(date).toLocaleString();
        if (endTime === '1970-1-1') {
            endTime = ''
        }
        this.setState({endTime: endTime, datevalue2: date})
    });

    //分站change事件
    substationChange = (val, option) => {
        val = Array.isArray(val) ? val : [val];

        val.forEach((item, index) => {
            if (Array.isArray(item)) {
                val = item;
            }
        });
        this.setState({subIdArr: val});
    };

    //分类change事件
    classicChange = (val, option) => {
        if (val === "") {
            this.setState({isTypeNull: 0})
        } else {
            this.setState({isTypeNull: 1})
        }
        this.setState({recycleTypeId: val});
    };

    //搜索
    searching() {
        axios.post('count/count/substatistics', {
            subList: this.state.subIdArr,
            recycleTypeId: this.state.recycleTypeId,
            beginTime: this.state.beginTime,
            endTime: this.state.endTime,
            pageSize: this.state.pageSize,
            pageNum: this.state.pageNum,
            isTypeNull: this.state.isTypeNull
        }).then((res) => {
            console.log(res);
            this.setState({
                data: res.data.data.pageInfo.list,
                total: res.data.data.pageInfo.total
            })
        }).catch((err) => {
            console.log(err)
        })
    }

    //回收品类集合
    getRecycleInfo() {
        axios.post('count/count/selecttypes').then((res) => {
            console.log(res.data.data);
            const recycleList = res.data.data;
            const classic = new Array(recycleList.length);
            recycleList.forEach((item, index) => {
                classic[index] = {
                    value: item.id,
                    label: item.title
                }
            });
            classic.unshift({
                value: '',
                label: '请选择'
            })
            this.setState({classic: classic});
        }).catch((e) => {
            console.log(e)
        })

    }

    // 选择全部记录还是当前页记录
    onExportChange(e) {
        this.setState({
            exportValue: e
        });
        if (e === 1) {
            this.setState({
                beginPage: 1,
                endPage: this.state.endPage
            })
        } else if (e === 2) {
            this.setState({
                beginPage: this.state.beginPage,
                endPage: this.state.beginPage,
            })
        } else if (e === 3) {
            this.setState({
                beginPage: this.state.beginPage,
                endPage: this.state.endPage,
            })
        }
    }

    //选择导出字段
    selectCheckbox(e) {
        this.setState({
            exportFields: e
        });

        if (e.indexOf('分站') !== -1) {
            this.setState({isSubShow: 1})
        } else {
            this.setState({isSubShow: 0})
        }
        if (e.indexOf('再回收资源品类') !== -1) {
            this.setState({isTypeShow: 1})
        } else {
            this.setState({isTypeShow: 0})
        }
        if (e.indexOf('回收重量(kg)') !== -1) {
            this.setState({isRecycleWeightShow: 1})
        } else {
            this.setState({isRecycleWeightShow: 0})
        }
        if (e.indexOf('回收支出(元)') !== -1) {
            this.setState({isRecycleExpendShow: 1})
        } else {
            this.setState({isRecycleExpendShow: 0})
        }
        if (e.indexOf('销售重量(kg)') !== -1) {
            this.setState({isSalesWeightShow: 1})
        } else {
            this.setState({isSalesWeightShow: 0})
        }

    }

    //导出
    export() {
        this.setState({dialogVisible3: true});
        var totalPage = Math.ceil(this.state.total / this.state.pageSize);
        this.setState({totalPage:totalPage})
    }

//确定导出
    exportSure() {

        var fileds = [];
        let checkboxData = this.state.checkboxData;
        let exportFields = this.state.exportFields;
        checkboxData.forEach((item) => {
            exportFields.forEach((subItem) => {
                if (item.name === subItem) {
                    fileds.push(item.type)
                }
            })
        });
        if (fileds.length < 2) {
            this.setState({dialogVisible: true, dialogInfo: '请至少选择两项，分站是必选项'});
        } else if (fileds.indexOf('subName') === -1) {
            this.setState({dialogVisible: true, dialogInfo: '分站是必选项'});
        }else if (this.state.beginPage > this.state.endPage ){
            this.setState({dialogVisible:true, dialogInfo: '结束页不能小于开始页'})
        } else {


            window.open('/count/count/subsexport?'
                + 'isSubShow='
                + this.state.isSubShow
                + '&isTypeShow='
                + this.state.isTypeShow
                + '&isTypeNull='
                + this.state.isTypeNull
                + '&isRecycleWeightShow='
                + this.state.isRecycleWeightShow
                + '&isRecycleExpendShow='
                + this.state.isRecycleExpendShow
                + '&isSalesWeightShow='
                + this.state.isSalesWeightShow
                + '&subList='
                + this.state.subIdArr
                + '&recycleTypeId='
                + this.state.recycleTypeId
                + '&beginPage='
                + this.state.beginPage
                + '&endPage='
                + this.state.endPage
                + '&pageSize='
                + this.state.pageSize
            );
        }

    }

    //单选框
    onChange(vap) {
        this.setState({vap});
    }

    setColumns(columns, data) {
        const dataList = [];
        for (var i = 0; i < columns.length; i++) {
            let total = 0;
            for (let j = 0; j < data.length; j++) {
                let value = data[j][columns[i]['property']];

                if (isNaN(value)) {
                    total = null
                    break;
                } else {
                    if (i === 3 || i === 5) {
                        total += parseFloat(value) / 1000;
                    } else if (i === 4) {
                        total += parseFloat(value) / 100;
                    }
                }
            }
            if (i === 3 || i === 5) {
                total = total.toFixed(2) + ' kg';
            }
            if (i === 4) {
                total = total.toFixed(2) + ' 元'
            }
            dataList[i] = total === '' ? total : total;
            dataList[0] = '合计'
        }
        return dataList;
    }

    render() {
        return (
            <div className='substation'>
                <Top></Top>
                <div className="pagecont">
                    <Nav sub='active'></Nav>
                    <div className="show_cont">
                        <div className="data_temp">
                            <DateSelect
                                dateChange1={this.dateChange1}
                                dateChange2={this.dateChange2}
                                value1={this.state.datevalue1}
                                value2={this.state.datevalue2}
                            ></DateSelect>

                            <SelectAddress
                                clearable={true}
                                value='请选择分站'
                                multiple={true}
                                buth='分站'
                                options={this.state.substation}
                                clsname="slct_substation"
                                selChange={this.substationChange}
                            ></SelectAddress>

                            <SelectAddress
                                clearable={true}
                                value='请选择分类'
                                multiple={false}
                                buth='分类'
                                options={this.state.classic}
                                clsname='slct_classic'
                                selChange={this.classicChange}
                            ></SelectAddress>
                            <div className="empty" style={{flex: '1'}}></div>
                            <div className="search">
                                <Button onClick={this.searching.bind(this)}><i class="el-icon-search mr-6"></i>搜索</Button>
                                <Button onClick={this.export.bind(this)}><i class="el-icon-upload mr-6"></i>导出</Button>
                            </div>
                        </div>
                        <div className="table_show">
                            <TableShow
                                columns={this.state.columns}
                                data={this.state.data}
                                total={this.state.total}
                                setPageNum={this.setPageNum}
                                setPageSize={this.setPageSize}
                                setFiles={this.setFiles}
                                pageNum={this.state.pageNum}
                                pageSize={this.state.pageSize}
                                setColumns={this.setColumns}
                            ></TableShow>
                        </div>
                    </div>
                </div>

                <Dialog title="导出" visible={this.state.dialogVisible3}
                        onCancel={() => this.setState({dialogVisible3: false})}>

                    <Dialog.Body>
                        <Form model={this.state.form}>

                            <Form.Item label="导出为">
                                <Select value="1" placeholder="请选择导出方式">
                                    <Select.Option label="Excel" value="1"></Select.Option>
                                </Select>
                            </Form.Item>
                            <Form.Item>
                                <Radio value="1" checked={this.state.exportValue === "1"}
                                       onChange={this.onExportChange.bind(this)}>全部记录</Radio>
                                <Radio value="2" checked={this.state.exportValue === "2"}
                                       onChange={this.onExportChange.bind(this)}>当前页记录</Radio>
                                <Radio value="3" checked={this.state.exportValue === "3"}
                                       onChange={this.onExportChange.bind(this)}>从</Radio>
                                <Input className='start' value={this.state.beginValue} onChange={(val) => {
                                    if ( val >this.state.totalPage || val < 0) {
                                        this.setState({dialogVisible: true, dialogInfo: '请输入正确的页数'});
                                    }else{

                                        this.setState({beginPage: val})
                                    }
                                }}></Input>
                                <span style={{margin: '0 5px'}}>到</span>
                                <Input className='end' value={this.state.endPage} onChange={(val) => {
                                    if ( val >this.state.totalPage || val < 0) {
                                        this.setState({dialogVisible: true, dialogInfo: '请输入正确的页数'});
                                    }else{
                                        this.setState({endPage: val})
                                    }
                                }}></Input>
                                <span>页</span>
                            </Form.Item>

                            <Form.Item label="导出字段">

                            </Form.Item>

                            <Form.Item>
                                <div className="check">
                                    <Checkbox.Group value={this.state.exportFields} onChange={this.selectCheckbox.bind(this)}>
                                        {
                                            this.state.checkboxData.map((item, index) => {
                                                return <Checkbox
                                                    key={index}
                                                    label={item.name}
                                                ></Checkbox>
                                            })
                                        }
                                    </Checkbox.Group>
                                </div>
                            </Form.Item>
                        </Form>
                    </Dialog.Body>

                    <Dialog.Footer className="dialog-footer">
                        <Button className="can" onClick={() => this.setState({dialogVisible3: false})}>取 消</Button>
                        <Button className="sur" type="primary" onClick={this.exportSure.bind(this)}>确 定</Button>
                    </Dialog.Footer>
                </Dialog>

                <div className='tishi' style={{zIndex: 100000}}>
                    <Dialog
                        title="提示"
                        size="tiny"
                        visible={this.state.dialogVisible}
                        onCancel={() => this.setState({dialogVisible: false})}
                        lockScroll={false}
                    >
                        <Dialog.Body>
                            <span>{this.state.dialogInfo}</span>
                        </Dialog.Body>
                        <Dialog.Footer className="dialog-footer">
                            <Button onClick={() => this.setState({dialogVisible: false})}>取消</Button>
                            <Button type="primary" onClick={() => this.setState({dialogVisible: false})}>确定</Button>
                        </Dialog.Footer>
                    </Dialog>
                </div>
            </div>
        );
    }
}

export default SubstationForm;